// ==================== src/traits/storage.rs ====================
//! 存储抽象trait定义
//!
//! 提供统一的存储接口抽象，支持多种存储后端实现
//! 包括通用存储、配置存储和服务存储三大类别
//!
//! # 设计原则
//! - 异步优先：所有操作均为异步接口
//! - 零成本抽象：trait设计不引入运行时开销
//! - 线程安全：所有实现必须满足Send + Sync
//! - 可扩展性：支持多种存储后端实现

use async_trait::async_trait;
use crate::{Result, ConfigItem, ServiceInstance};
use std::collections::HashMap;

/// 存储抽象trait
#[async_trait]
pub trait Storage: Send + Sync + std::fmt::Debug {
    /// 获取数据
    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;
    
    /// 存储数据
    async fn put(&self, key: &str, value: &[u8]) -> Result<()>;
    
    /// 删除数据
    async fn delete(&self, key: &str) -> Result<()>;
    
    /// 前缀扫描
    async fn scan(&self, prefix: &str) -> Result<Vec<(String, Vec<u8>)>>;
    
    /// 批量获取
    async fn batch_get(&self, keys: &[String]) -> Result<HashMap<String, Vec<u8>>>;
    
    /// 批量存储
    async fn batch_put(&self, data: &HashMap<String, Vec<u8>>) -> Result<()>;
    
    /// 批量删除
    async fn batch_delete(&self, keys: &[String]) -> Result<()>;
    
    /// 检查键是否存在
    async fn exists(&self, key: &str) -> Result<bool>;
    
    /// 获取所有键
    async fn keys(&self, pattern: &str) -> Result<Vec<String>>;
    
    /// 清空所有数据
    async fn clear(&self) -> Result<()>;
}

/// 配置存储trait
#[async_trait]
pub trait ConfigStorage: Send + Sync + std::fmt::Debug {
    /// 获取配置
    async fn get_config(&self, namespace: &str, group: &str, data_id: &str) -> Result<Option<ConfigItem>>;
    
    /// 保存配置
    async fn save_config(&self, config: &ConfigItem) -> Result<()>;
    
    /// 删除配置
    async fn delete_config(&self, namespace: &str, group: &str, data_id: &str) -> Result<()>;
    
    /// 获取配置列表
    async fn list_configs(&self, namespace: &str, group: Option<&str>) -> Result<Vec<ConfigItem>>;
    
    /// 获取配置历史
    async fn get_config_history(&self, namespace: &str, group: &str, data_id: &str, limit: usize) -> Result<Vec<ConfigItem>>;
}

/// 服务存储trait
#[async_trait]
pub trait ServiceStorage: Send + Sync + std::fmt::Debug {
    /// 注册服务实例
    async fn register_instance(&self, instance: &ServiceInstance) -> Result<()>;
    
    /// 注销服务实例
    async fn deregister_instance(&self, namespace: &str, group: &str, service_name: &str, instance_id: &str) -> Result<()>;
    
    /// 获取服务实例
    async fn get_instance(&self, namespace: &str, group: &str, service_name: &str, instance_id: &str) -> Result<Option<ServiceInstance>>;
    
    /// 获取服务的所有实例
    async fn get_all_instances(&self, namespace: &str, group: &str, service_name: &str) -> Result<Vec<ServiceInstance>>;
    
    /// 更新实例健康状态
    async fn update_instance_health(&self, namespace: &str, group: &str, service_name: &str, instance_id: &str, healthy: bool) -> Result<()>;
    
    /// 获取所有服务
    async fn get_all_services(&self, namespace: &str, group: Option<&str>) -> Result<Vec<String>>;

    /// 前缀扫描
    async fn scan(&self, prefix: &str) -> Result<Vec<(String, Vec<u8>)>>;
}